package permission

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminlog"
	"private-domain-overseas-service/tools/ent/predicate"
)

type AdminLogDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminLogDao(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLogDao {
	return &AdminLogDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// AdminLogCreate - 创建后台日志
func (l *AdminLogDao) AdminLogCreate(adminLog *ent.AdminLog, tx *ent.Tx) error {
	err := tx.AdminLog.Create().
		SetAdminLogAccount(adminLog.AdminLogAccount).
		SetAdminLogIP(adminLog.AdminLogIP).
		SetAdminLogOperateSystem(adminLog.AdminLogOperateSystem).
		SetAdminLogPage(adminLog.AdminLogPage).
		SetAdminLogURL(adminLog.AdminLogURL).
		SetAdminLogBrowser(adminLog.AdminLogBrowser).
		SetAdminLogExtraInfo(adminLog.AdminLogExtraInfo).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// AdminLogConditionsPageAll - 查询后台日志列表
func (l *AdminLogDao) AdminLogConditionsPageAll(req *types.AdminLogListRequest, conditions []predicate.AdminLog) ([]*ent.AdminLog, int, error) {
	offset := common.Offset(req.Current, req.PageSize)

	adminUsers, err := l.svcCtx.Orm.AdminLog.Query().
		Where(conditions...).
		Where(adminlog.IsDeleteEQ(bizadmin.NotDelete)).
		Offset(int(offset)).
		Limit(int(req.PageSize)).
		All(l.ctx)

	if err != nil {
		return nil, 0, err
	}

	total, err := l.svcCtx.Orm.AdminLog.Query().
		Where(conditions...).
		Where(adminlog.IsDeleteEQ(bizadmin.NotDelete)).
		Count(l.ctx)

	return adminUsers, total, nil
}
